/**
 * Created by lihao on 2017/6/28.
 */
const keystone = require('keystone');
const Promise = require('bluebird');
const _ = require('lodash');
const Post = keystone.list('SystemConf');
exports = module.exports = function (req, res) {
	let reqQuery = _.omit(_.assign(req.query, req.body,req.param), ['password']);
	let omitFueld = ['password', 'isAdmin', '__v'];
	let optionalExpression = _.transform(omitFueld, function (r, val) {
		r[val] = 0;
	}, {});
	if (_.has(reqQuery, 'id') && reqQuery.id != '') {
		Post.model.findById(reqQuery.id).exec(function (err, item) {
			if (err) res.json({code: 0, message: '请求失败'});
			if (_.isEmpty(item)) res.json({code: 0, message: '找不到用户'});
			item.getUpdateHandler(req).process(reqQuery, {flashErrors: true, logErrors: true}, function (err) {
				if (err) return res.json({code: 0, message: '修改失败'});
				res.json({code: 1, message: '修改成功'});
			});

		});
	} else if (_.has(reqQuery, 'ids') && reqQuery.ids != '') {
		Promise.map(reqQuery.ids.split(','),function (id) {
			return new Promise(function (resolve,reject) {
				Post.model.findById(id).exec(function (err, item) {
					if (err) reject(err);
					if (_.isEmpty(item)) if (err) reject(err);
					item.getUpdateHandler(req).process(_.omit(reqQuery,'id'), {flashErrors: true, logErrors: true}, function (err) {
						if (err) reject(err);
						return resolve();
					});

				});
			})	
		})
			.then(function () {
				res.json({code: 1, message: '修改成功'});
				return null;
			})
			.catch(function (err) {
				if (err) res.json({code: 0, message: '请求失败'});
			})
    	
	} else {
		return res.json({code: 0, message: 'ID为空'});
	}

};
